package com.yunzhi.net.retrofit;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yunzhi.net.config.ApiConfig;
import com.yunzhi.net.config.HostType;
import com.yunzhi.net.interceptor.HttpCacheInterceptor;
import com.yunzhi.net.interceptor.HttpHeaderInterceptor;
import com.yunzhi.net.interceptor.LoggingInterceptor;
import com.yunzhi.net.utils.Utils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;


/**
 * Author by Mr.Meng
 * created 2019/5/15
 *
 * @desc 根据Api接口类生成Api实体
 */
public class RetrofitFactory {

    private static class RetrofitFactoryHolder {
        private static final RetrofitFactory INSTANCE = new RetrofitFactory();
    }

    public static RetrofitFactory getInstance() {
        return RetrofitFactoryHolder.INSTANCE;
    }


    private final Retrofit retrofit;

    private RetrofitFactory() {

        // 指定缓存路径,缓存大小100Mb
        File cacheFile = new File(Utils.getApp().getCacheDir(), "HttpCache");
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100);

        OkHttpClient httpClient = new OkHttpClient().newBuilder()
                .readTimeout(ApiConfig.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(ApiConfig.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(LoggingInterceptor.getLoggingInterceptor())
                .addInterceptor(new HttpHeaderInterceptor())
                .addNetworkInterceptor(new HttpCacheInterceptor())
                .cache(cache)
                .build();

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();

        retrofit = new Retrofit.Builder()
                .client(httpClient)
                .addConverterFactory(ResponseConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(ApiConfig.getInstance().getServerUrl(HostType.MAIN_HOST))
                .build();

    }


    /**
     * 根据Api接口类生成Api实体
     *
     * @param clazz 传入的Api接口类
     * @return Api实体类
     */
    public <T> T create(Class<T> clazz) {
        return retrofit.create(clazz);
    }


}
